<template>
  <!-- 主播管理 -->
  <a-spin class="anchor-review" tip="加载中..." :spinning="isLoading">
    <!-- 筛选 -->
    <div class="filter">
      <div class="l search-box-item">
        <!-- 筛选条件：站点、产品套餐ID/名称、小程序上线状态、SPU审核状态、商品上线时间、快手审核时间 -->
        <div>
          <span class="label-text-small">站点选择：</span>
          <a-select class="search-width-small" show-search :allowClear="true" @change="changeLocation" v-model="search.localtionId" placeholder="请选择站点" :filter-option="filterOption">
            <a-select-option :value="-1">全部</a-select-option>
            <a-select-option v-for="item in allStation" :key="item.id" :value="item.id">{{ item.city }}</a-select-option>
          </a-select>
        </div>
        <div>
          <span class="label-text-middle">产品套餐ID/名称：</span>
          <a-input-search class="search-width-small" type="text" placeholder="产品套餐ID/名称" allowClear v-model="search.keyWord" @search="handleByQueryCond" />
        </div>
        <div>
          <span class="label-text-middle">小程序上线状态：</span>
          <a-select class="search-width-small" placeholder="请选择状态" v-model="search.kwaiStatus" @change="handleByQueryCond">
            <a-select-option v-for="item in programStatus" :key="item.value" :value="item.value">{{ item.name }}</a-select-option>
          </a-select>
        </div>
        <div>
          <span class="label-text-small">商品上线时间：</span>
          <a-range-picker class="search-width-middle" @change="handleByQueryCond" v-model="search.selectDateGood" />
        </div>
        <div>
          <span class="label-text-small">快手审核时间：</span>
          <a-range-picker class="search-width-middle" @change="handleByQueryCond" v-model="search.selectDate" />
        </div>
        <div>
          <span class="label-text-small">SPU审核状态：</span>
          <a-select class="search-width-small" placeholder="请选择SPU审核状态" v-model="search.spuStatus" @change="handleByQueryCond">
            <a-select-option v-for="item in spuStatus" :key="item.value" :value="item.value">{{ item.name }}</a-select-option>
          </a-select>
        </div>
      </div>

      <div>
        <a-button type="primary" @click="handleByQueryCond" style="background:#1d6fe9">查询</a-button>
        <a-button @click="reset">重置</a-button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="main-body self-time-line">
      <a-table :columns="tableColumns" :pagination="false" :data-source="spuList" :scroll="{ x: 900, y: tableHeight }" rowKey="id">
        <!-- 产品相关 -->
        <!-- 产品套餐信息：产品ID、产品名称、产品品类、套餐ID、套餐名称、站点、产品经理、合同名称、售价/原价、剩余库存 -->
        <template slot="productId" slot-scope="text, record">
          <div class="product-item-box">
            <div>
              <p><span class="font-weight-bold">产品ID：</span>{{ record.productId || '无' }}</p>
              <p><span class="font-weight-bold">产品名称：</span>{{ record.productName || '无' }}</p>
              <p><span class="font-weight-bold">产品品类：</span>{{ record.productType || '无' }}</p>
              <p><span class="font-weight-bold">套餐ID：</span>{{ record.productItemId || '无' }}</p>
              <p><span class="font-weight-bold">套餐名称：</span>{{ record.productItemName || '无' }}</p>
            </div>
            <div>
              <p><span class="font-weight-bold">站点：</span>{{ record.city || '无' }}</p>
              <p><span class="font-weight-bold">产品经理：</span>{{ record.pmName || '无' }}</p>
              <p><span class="font-weight-bold">合同名称：</span>{{ record.contractName || '无' }}</p>
              <p><span class="font-weight-bold">售价/原价：</span>{{ record.salePriceYuan || 0 }}/{{ record.originPriceYuan || 0 }}</p>
              <p><span class="font-weight-bold">剩余库存：</span>{{ record.stockAmount || 0 }}</p>
            </div>
          </div>
        </template>
        <!-- 订单量 -->
        <!-- 套餐订单信息：销量、核销量、退款量、快手分销佣金、佣金(大中小)-->
        <template slot="productItemSales" slot-scope="text, record">
          <p><span class="font-weight-bold">销量：</span>{{ record.productItemSales || 0 }}</p>
          <p><span class="font-weight-bold">核销量：</span>{{ record.productItemCompleteSales || 0 }}</p>
          <p><span class="font-weight-bold">退款量：</span>{{ record.productItemRefundSales || 0 }}</p>
          <p><span class="font-weight-bold">快手分销佣金：</span>{{ record.kwaiCommissionMoneyYuan || 0 }}</p>
          <!-- <p>
            <span class="font-weight-bold">
              快手分销佣金
              <a-tooltip placement="right" overlayClassName="time-line-tooltip">
                <template slot="title">
                  已核销3天后到账的CPS佣金金额(不包含核销未满3天的金额)
                </template>
                <a-icon type="question-circle" :style="{ fontSize: '13px', color: '#4E5969' }" />
              </a-tooltip>
              ：
            </span>
            {{ record.productItemCps || 0 }}
          </p> -->
          <p><span class="font-weight-bold">佣金：</span>{{ record.sysCommissionMoney || '无' }}</p>
        </template>
        <!-- 套餐状态 -->
        <!-- 套餐状态：联联周边游(上线、下线+时间)、POI已绑定/总数(1/2/3/4/5 + 时间  取其中之一即可  -->
        <template slot="statusFlowList" slot-scope="text, record">
          <a-timeline>
            <a-timeline-item :color="item.lightFlag ? '#57AE59' : 'rgb(206, 205, 205)'" :class="[item.lightFlag ? '' : 'no-line']" v-for="item in record.statusFlowList" :key="item.sort">
              <div class="min-hei-auto">
                <div class="flex-title">
                  <p class="title-text">
                    {{ item.title || 'Title' }}
                    <a-tooltip placement="right" overlayClassName="time-line-tooltip" v-if="item.remark">
                      <template slot="title">
                        <span>{{ item.remark || '' }}</span>
                      </template>
                      <a-icon type="question-circle" :style="{ fontSize: '13px', color: '#4E5969' }" />
                    </a-tooltip>
                  </p>
                  <div v-if="item.statusDesc" :class="['tag-box', item.color === 1 ? 'tag-box-gray' : item.color === 2 ? 'tag-box-green' : 'tag-box-red']">{{ item.statusDesc }}</div>
                </div>
                <p class="time-text">{{ item.time || '' }}</p>
                <a-tooltip placement="right" overlayClassName="time-line-tooltip" v-if="item.sort !== 1 && item.reason && item.reason.length === 1 && item.reason[0].length > 12">
                  <template slot="title">
                    <div>1、{{ item.reason[0] }}</div>
                  </template>
                  <div class="reason-text">1、{{ item.reason[0] }}</div>
                </a-tooltip>
                <div class="reason-text" v-else-if="item.sort !== 1 && item.reason && item.reason.length === 1">1、{{ item.reason[0] }}</div>
                <a-tooltip placement="right" overlayClassName="time-line-tooltip" v-else-if="item.sort !== 1 && item.reason && item.reason.length > 1">
                  <template slot="title">
                    <div v-for="(v, index) in item.reason" :key="v">{{ index + 1 }}、{{ v }}</div>
                  </template>
                  <div class="reason-text" v-for="(v, index) in item.reason.slice(0, 1)" :key="v">{{ index + 1 }}、{{ v }}</div>
                  <div class="shou-more">显示更多>></div>
                </a-tooltip>
              </div>
            </a-timeline-item>
          </a-timeline>
        </template>
        <!-- 时间 -->
        <!-- 时间：BD上线时间、产品过期时间、SPU提审时间、SPU审核时间、团购过期时间 -->
        <template slot="expirTime" slot-scope="text, record">
          <p><span class="font-weight-bold">BD上线时间：</span>{{ record.releaseTime || '无' }}</p>
          <p><span class="font-weight-bold">产品过期时间：</span>{{ record.validEndDate || '无' }}</p>
          <p><span class="font-weight-bold">SPU提审时间：</span>{{ record.applyTime || '无' }}</p>
          <p><span class="font-weight-bold">SPU审核时间：</span>{{ record.auditTime || '无' }}</p>
          <p><span class="font-weight-bold">快手团购过期时间：</span>{{ record.expirTime || '无' }}</p>
        </template>
        <!-- 操作按钮 -->
        <!-- POI管理 、更新状态、 上架快手(调快手接口 批量上架)、下架快手(调快手接口 批量下架)、提交快手审核 -->
        <template slot="action" slot-scope="text, record">
          <a-button type="link" href="javascript:;" size="small" @click="toSpuManag(record.productItemId)">POI管理</a-button>

          <!-- 1 在线 0 下线 -->
          <a-button type="link" href="javascript:;" size="small" @click="handleUpDownGoods(record.productId, record.productItemId, 1)">上架快手</a-button>
          <a-button type="link" href="javascript:;" size="small" @click="handleUpDownGoods(record.productId, record.productItemId, 0)">下架快手</a-button>
          <a-button type="link" href="javascript:;" size="small" @click="submitKwaiAudit(record.productItemId)">提交快手审核</a-button>
          <!-- 对SPU状态为“审核中”的产品提供按钮，刷新SPU状态 -->
          <a-button type="link" href="javascript:;" size="small" @click="spuAudit(record.productItemId)">查询快手审核</a-button>
        </template>
      </a-table>
    </div>

    <!-- 分页 -->
    <div class="paging-container">
      <a-pagination
        :pageSize="search.pageSize"
        v-model="search.pageIndex"
        :total="pagination.total"
        showQuickJumper
        showLessItems
        :showTotal="(total) => `共 ${total} 条`"
        style="margin: 10px auto;"
        @change="handlePageChange"
      />
    </div>
    <quality-submit
      v-model="isShowQuality"
      :qualityList="qualityList"
      :postQualityList="postQualityList"
      :marketingList="marketingList"
      :getProductItemId="productItemId"
      @onCancel="handleCloseQuality"
      @callback="query()"
      :type="1"
    ></quality-submit>
  </a-spin>
</template>

<script>
import { getCommonApiSearch } from '@/service'
import { kwaiProductModify, kwaiSpuList, kwaiProductMount, kwaiSpuSubmit } from '@/service/ksService'
import moment from 'moment'
import debounce from 'lodash/debounce'
import { columnsConfig } from './columns'
import qualitySubmit from './components/qualitySubmit'
export default {
  name: 'spuManageAdmin',
  data() {
    // 节流
    this.getAllStation = debounce(this.getAllStation, 800)
    return {
      moment,
      // loading是否显示
      isLoading: false,
      cpsConfigFlag: false,
      pagination: {
        total: 0
      },
      // 全部站点
      allStation: [],
      // table数据查询条件
      search: {
        keyWord: '',
        selectDate: [],
        selectDateGood: [],
        spuStatus: '',
        kwaiStatus: '',
        localtionId: '',
        pageIndex: 1,
        pageSize: 10
      },
      // spu列表
      spuList: [],
      tableColumns: columnsConfig.spuColumns,

      isShowQuality: false,
      isSubQualityLoading: false,
      qualityList: [],
      marketingList: [],
      inputVisible: false,
      inputValue: '',
      productItemId: 0,
      postQualityList: []
    }
  },
  components: {
    qualitySubmit
  },
  computed: {
    // SPU状态
    spuStatus() {
      return [
        {
          name: '全部',
          value: ''
        },
        {
          name: '未提审',
          value: 0
        },
        {
          name: '审核中',
          value: 1
        },
        {
          name: '上架',
          value: 2
        },
        {
          name: '下架',
          value: 5
        },
        {
          name: '审核拒绝',
          value: 3
        }
      ]
    },
    programStatus() {
      return [
        {
          name: '全部',
          value: ''
        },
        {
          name: '在线',
          value: 1
        },
        {
          name: '下线',
          value: 0
        }
      ]
    }
  },

  methods: {
    /**
     * 通过条件查询
     * @returns {void}
     */
    handleByQueryCond() {
      this.search.pageIndex = 1
      this.setPath(this.getParams())
      this.query()
    },

    /**
     * 分页
     * @param {number} num 当前页码
     * @returns {void}
     */
    handlePageChange(num) {
      this.search.pageIndex = num
      this.setPath(this.getParams())
      this.query()
    },

    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },

    getAllStation(e) {
      console.log(e)
      getCommonApiSearch({ keywords: e }).then((res) => {
        this.allStation = res
      })
    },

    // 选择了站点
    changeLocation() {
      this.search.pageIndex = 1
      this.initQuery()
    },

    // 拿参数
    getParams() {
      // const { pageIndex, pageSize } = this.pagination
      const { keyWord, spuStatus, kwaiStatus, selectDate = [], localtionId, selectDateGood = [], pageIndex, pageSize } = this.search
      return {
        pageIndex,
        pageSize,
        kwaiStatus,
        spuStatus,
        keyWord,
        localtionId,
        startTime: selectDate[0] ? moment(selectDate[0]).format('YYYY-MM-DD 00:00:00') : undefined,
        endTime: selectDate[1] ? moment(selectDate[1]).format('YYYY-MM-DD 23:59:59') : undefined,
        releaseStartTime: selectDateGood[0] ? moment(selectDateGood[0]).format('YYYY-MM-DD 00:00:00') : undefined,
        releaseEndTime: selectDateGood[1] ? moment(selectDateGood[1]).format('YYYY-MM-DD 23:59:59') : undefined
      }
    },
    // 设置搜索
    setSearch() {
      const { pageIndex, keyWord, startTime, endTime, spuStatus, kwaiStatus, releaseStartTime, releaseEndTime, localtionId } = this.$route.query
      const queryLen = Object.keys(this.$route.query).length
      if (queryLen) {
        this.search = {
          pageIndex: isNaN(pageIndex) ? 1 : +pageIndex,
          pageSize: 10,
          localtionId: isNaN(localtionId) ? null : +localtionId,
          keyWord: keyWord || '',
          spuStatus: isNaN(spuStatus) ? '' : spuStatus === 0 ? '0' : +spuStatus,
          kwaiStatus: +kwaiStatus || '',
          selectDate: startTime && endTime ? [startTime, endTime] : [],
          selectDateGood: releaseStartTime && releaseEndTime ? [releaseStartTime, releaseEndTime] : []
        }
      }
    },
    // 重置
    reset() {
      this.search = {
        keyWord: '',
        selectDate: [],
        selectDateGood: [],
        spuStatus: '',
        kwaiStatus: '',
        localtionId: '',
        pageIndex: 1,
        pageSize: 10
      }
      const { path } = this.$route
      this.$router
        .replace({
          path,
          query: {}
        })
        .catch(() => {})
      this.initQuery()
    },
    // 初始化
    initQuery() {
      this.search.pageSize = 10
      this.setPath(this.getParams())
      this.query()
    },

    /**
     * 获取spu信息列表
     * @returns {Promise<void>}
     */
    query() {
      this.isLoading = true
      kwaiSpuList(this.getParams())
        .then((rs) => {
          console.log(rs)
          this.spuList = Object.freeze(rs.spuListData) || []
          this.pagination.total = rs.total || 0
          this.cpsConfigFlag = rs.cpsConfigFlag || false
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 储存搜索字段
    setPath(origin) {
      const { path } = this.$route
      const query = {}
      for (let key in origin) {
        if (origin[key] || origin[key] === 0) query[key] = origin[key]
      }
      if (query.pageIndex <= 1) delete query.pageIndex
      delete query.pageSize
      this.$router
        .replace({
          path,
          query: {
            ...query
          }
        })
        .catch(() => {})
    },
    toSpuManag(productItemId = '') {
      // 产品ID
      this.$router.push({
        path: '/kwaiManage/poiManagForSpu',
        query: {
          productItemId
        }
      })
    },
    // spu审核查询
    spuAudit(productItemId = '') {
      this.isLoading = true
      kwaiProductMount({ productItemId })
        .then(() => {
          this.query()
        })
        .finally(() => {
          this.isLoading = false
        })
        .catch(() => {
          this.isLoading = false
        })
    },
    handleCloseQuality() {
      this.isShowQuality = false
      this.productItemId = 0
      this.marketingList = []
      this.postQualityList = []
      this.qualityList = []
    },
    // 提交快手审核
    submitKwaiAudit(productItemId = '') {
      this.isLoading = true
      kwaiSpuSubmit({ productItemId })
        .then((res) => {
          console.log(res)
          this.query()
        })
        .finally(() => {
          this.isLoading = false
        })
        .catch(() => {
          this.isLoading = false
        })
    },
    /*
      上下架
      type：1 上架 0 下架 ===>（kwaiVisible 1上线，0不上线）
      id：产品id
    */
    handleUpDownGoods(id = '', productItemId = '', type = 0) {
      const _this = this
      this.$confirm({
        title: type ? '上线快手' : '下线快手',
        content: type ? '确定要上线吗？' : '操作下线快手后，产品将从快手小程序下线，即在快手C端不显示，是否确认下线',
        onOk() {
          // 发送确认上架架请求并刷新
          return kwaiProductModify({ kwaiVisible: type, bizProductId: id, productItemId })
            .then(() => {
              _this.$messageSend.success('操作成功')
              _this.query()
            })
            .catch((err) => err)
        },
        onCancel() {}
      })
    }
  },

  mounted() {
    // todo 待删除
    // this.initQuery()
    // 获取所有站点
    getCommonApiSearch()
      .then((res = []) => {
        this.allStation = res
        this.setSearch()
        this.initQuery()
      })
      // 获取失败依然继续请求列表数据
      .catch((err) => err)
  }
}
</script>

<style lang="less" scoped>
.anchor-review {
  padding: 16px;
}
.search-box-item {
  width: calc(100% - 150px);
}
table tbody td div {
  margin-top: 2px;
}
/deep/ table tbody td a {
  margin-right: 0;
}
.search-box {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  flex-wrap: wrap;
  > div {
    margin-right: 15px;
    margin-bottom: 5px;
  }
}
p {
  margin-bottom: 5px;
  font-size: 13px;
}
</style>
